package com.example.springbootmybatis.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.springbootmybatis.common.PageResult;
import com.example.springbootmybatis.common.RedisUtils;
import com.example.springbootmybatis.common.ResourceSetting;
import com.example.springbootmybatis.entity.UserTab;
import com.example.springbootmybatis.param.UserParam;
import com.example.springbootmybatis.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 用户操作
 */
@Controller  //标记为控制器
@RequestMapping("/user")//访问该api的路径  http://localhost:8081/user/...   user即为此处标记
public class UserController {

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Qualifier("user1")
    @Autowired  //使用spring依赖注入对应的service，以调用里面的实现方法，注意这里用的是接口，非实现类
    private IUserService userService;

    //自定义的资源配置类，从yml配置文件获取值
    @Autowired
    private ResourceSetting resourceSetting;

    @Autowired
    private RedisUtils redisUtils;


    @RequestMapping("/alluser")//访问该方法的路径  http://localhost:8081/user/alluser   alluser即为此处标记
    @ResponseBody//该方法返回的数据为json格式
    public JSONObject alluser() {
        JSONObject json = new JSONObject();
        List<UserTab> list = userService.selectAllUser();
        json.put("list", list);
//        redisTemplate.opsForValue().set("key", "11111");
//
//        logger.info("key", redisTemplate.opsForValue().get("key"));
        redisUtils.set("key", "445623");
        logger.info("key=============" + redisUtils.get("key"));
        return json;
    }

    //返回首页
    @RequestMapping("/list")
    @ResponseBody
    public ModelAndView list() {
        List<UserTab> list = userService.selectAllUser();
        ModelAndView mv = new ModelAndView();
        mv.addObject("list", list);//数据
        mv.setViewName("index");//页面
        return mv;
    }

    @RequestMapping("/getuserbyid")
    @ResponseBody
    public String getUserByid(Integer id) {
        if (id != null) {
            JSONObject jsonObject = new JSONObject();
            UserTab u = userService.getUserByid(id);
            jsonObject.put("u", u);
            return jsonObject.toString();
        }
        return null;
    }

    /**
     * 访问路径   http://localhost:8081/user/pagedemo?id=1
     *
     * @param id
     * @return
     */
    @GetMapping("pagedemo")
    public ModelAndView pagedemo(Integer id) {
        ModelAndView mv = new ModelAndView();
        if (id != null) {
            UserTab u = userService.getUserByid(id);
            //u将以key_value形式存在页面模型中，key为userTab,可自定义key，即对象类名首字母小写
            mv.addObject(u);
//            mv.addObject("userTab", u);//自定义key

            //u将以key_value形式存在页面模型中，key为userTabList，即对象类名首字母小写+List
            List<UserTab> list = userService.selectAllUser();
            mv.addObject(list);
        }
        mv.setViewName("test/demo");
        return mv;
    }


    @RequestMapping("/add")
    public ModelAndView add(UserTab user, MultipartFile faces) throws IOException {
        String img = "";
        if (faces.getOriginalFilename() != null && !faces.getOriginalFilename().equals("")) {//上传了文件在进来
            //处理图片名称
            String picName = UUID.randomUUID() + faces.getOriginalFilename().substring(faces.getOriginalFilename().lastIndexOf("."));
            String path = resourceSetting.getImg_file_path(); //设置存储位置
            //日期格式化 sim.format日期转字符串    sim.parse字符串装日期
            SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
            String data = sim.format(new Date());
            //整体路径
            String dirName = resourceSetting.getDir_name() + data;
            File dirFile = new File(path + dirName);
            if (!dirFile.exists()) {  //创建文件夹
                dirFile.mkdirs();
            }
            File targetFile = new File(path + dirName, picName);
            faces.transferTo(targetFile);  // 保存文件
            img = dirName + "/" + picName;
        }

        if (img == null || img.equals("")) {
            user.setFace(user.getFace());
        } else {
            user.setFace(img);
        }

        ModelAndView mv = new ModelAndView();
        if (user.getId() == null) {
            userService.addUser(user);
        } else {
            userService.updateUser(user);
        }
        mv.setViewName("redirect:list");
        return mv;
    }

    @ResponseBody
    @RequestMapping("/del")
    public String del(Integer id) {
        if (id != null) {
            userService.del(id);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg", "删除成功");
//        return "redirect:list";
        return jsonObject.toString();
    }

    /**
     * 分页查询人员信息
     *
     * @param pageNum  当前页
     * @param pageSize 页面大小
     * @param userName 查询条件
     * @return
     */
    @RequestMapping("/getUserByPage")
    @ResponseBody
    public JSONObject getUserByPage(Integer pageNum, Integer pageSize, String userName) {
        PageResult pages = userService.getUserByPage(pageNum, pageSize, userName);
        JSONObject json = new JSONObject();
        json.put("pages", pages);
        return json;
    }

    /**
     * 分页查询人员详细信息
     *
     * @param userParam 查询条件
     * @return
     */
    @RequestMapping("/getUserDetailByPage")
    @ResponseBody
    public JSONObject getUserDetailByPage(UserParam userParam) {
        PageResult pages = userService.getUserDetailByPage(userParam);
        JSONObject json = new JSONObject();
        json.put("pages", pages);
        return json;
    }
    //返回登录页
    @RequestMapping("/tologin")
    @ResponseBody
    public ModelAndView tologin() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("login");//页面
        return mv;
    }
    @PostMapping("/login")
    public String main(UserTab user, HttpSession session, Model model){ //RedirectAttributes
        user= userService.login(user);
        if(user != null){
            //把登陆成功的用户保存起来
            session.setAttribute("loginUser",user);
            //登录成功重定向到main.html;  重定向防止表单重复提交
            return "redirect:/user/list";
        }else {
            model.addAttribute("msg","账号密码错误");
            //回到登录页面
            return "login";
        }

    }
}
